var http = require('http');
var qs = require('querystring');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
    maxSockets: 5,
    maxFreeSockets: 2,
    timeout: 60000,
    freeSocketKeepAliveTimeout: 30000
});

var defaultOptions = {
    host: '127.0.0.1',
    port: 8888,
    headers: {
        'Content-Type': 'application/json'
    },
    agent: keepaliveAgent
};

var getOptions = function (obj) {
    var result = {};
    for (var key in defaultOptions) {
        result[key] = defaultOptions[key];
    }
    for (var key in obj) {
        result[key] = obj[key];
    }
    return result;
};

/************************** 模拟 get 请求 ******************************/

var getData = function () {

    var options = getOptions({
        path: '/services/user/1234.json?' + qs.stringify({id: 100}),
        method: 'GET'
    });

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.end();
};

getData();

/************************** 模拟 post 请求 ******************************/

var postData = function () {

    var options = getOptions({
        path: '/services/user/register.json',
        method: 'POST'
    });

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.write(JSON.stringify({id: 123, username: 'Tom'}));

    req.end();
};

postData();

/************************** 连接 状态 ******************************/

setTimeout(function () {
    console.log('agent status: %j', keepaliveAgent.getCurrentStatus());
}, 5000);
